package com.ideaaedi.zoo.commonbase.decorator;

import com.alibaba.ttl.TtlRunnable;
import org.springframework.core.task.TaskDecorator;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

/**
 * ttl 装饰器
 */
public class TtlTaskDecorator implements TaskDecorator {

    private final TaskDecorator[] taskDecoratorChain;

    public TtlTaskDecorator(@Nullable TaskDecorator... taskDecoratorChain) {
        this.taskDecoratorChain = taskDecoratorChain;
    }

    @NonNull
    @Override
    public Runnable decorate(@NonNull Runnable runnable) {
        if (taskDecoratorChain == null || taskDecoratorChain.length == 0) {
            return TtlRunnable.get(runnable, true, true);
        }
        Runnable wrapedRunnable = runnable;
        for (TaskDecorator taskDecorator : taskDecoratorChain) {
            wrapedRunnable = taskDecorator.decorate(wrapedRunnable);
        }
        return TtlRunnable.get(wrapedRunnable, true, true);
    }

}